package im.composer.persistent.xstream.converter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;

import org.apache.commons.codec.binary.Base64;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class SequenceConverter implements Converter {

	@Override
	public boolean canConvert(@SuppressWarnings("rawtypes") Class arg0) {
		return Sequence.class.isAssignableFrom(arg0);
	}

	@Override
	public void marshal(Object arg0, HierarchicalStreamWriter arg1, MarshallingContext arg2) {
		Sequence seq = (Sequence) arg0;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			MidiSystem.write(seq, MidiSystem.getMidiFileTypes()[0], baos);
		} catch (IOException e) {
		}
		arg1.setValue(Base64.encodeBase64String(baos.toByteArray()));
	}

	@Override
	public Object unmarshal(HierarchicalStreamReader arg0, UnmarshallingContext arg1) {
		byte[] b = Base64.decodeBase64(arg0.getValue());
		ByteArrayInputStream bais = new ByteArrayInputStream(b);
		Sequence seq = null;
		try {
			seq = MidiSystem.getSequence(bais);
		} catch (InvalidMidiDataException | IOException e) {
		}
		return seq;
	}

}
